<template>
  <a-modal :open="props.open" title="批量导入" width="1000px" :destroy-on-close="true" @cancel="handleCancel">
    <div class="bulk-import-modal">
      <a-steps :current="current" :items="items" />
      <div class="steps-content">
        <!-- 1：上传文件 -->
        <div v-if="current === 0">
          <!-- 上传文件：正常数据显示部分 -->
          <div v-if="!errorData" class="regular-data-wrap">
            <div class="template-data">
              <div class="title">填写数据</div>
              <div>
                <a-button size="large" style="width: 100%; color: rgba(21, 23, 27, 0.95)" @click="downloadTemplate">
                  <DownloadOutlined />
                  下载模板
                </a-button>
                <div class="tips">
                  <img src="@/assets/img/question-line.svg" />请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除
                </div>
              </div>
            </div>

            <div class="file-upload">
              <div class="title">上传文件</div>
              <div>
                <a-upload-dragger
                  v-model:fileList="fileList"
                  name="file"
                  :multiple="false"
                  :before-upload="beforeUpload"
                  :show-upload-list="false"
                >
                  <img class="mt-16" src="@/assets/img/drag-upload.svg" alt="" />
                  <p class="ant-upload-text">将文件拖拽至此处，或点此上传</p>
                </a-upload-dragger>
                <div v-if="fileName" class="filename-box">
                  <p>{{ fileName }}</p>
                  <DeleteOutlined class="icon" @click="delFile" />
                </div>
                <div class="tips mt-36">
                  <img src="@/assets/img/question-line.svg" />请上传后缀名为xls
                  或xlsx（即Excel）格式的文件，文件大小不得大于10M，单次最多支持导入5000条数据
                </div>
              </div>
            </div>

            <!-- 特别提示悬浮 -->
            <div class="special-tips">
              <div class="warning-title">
                <img src="@/assets/img/error-warning-line.svg" style="margin-right: 8px" alt="" />
                特别提示
              </div>
              <div class="text">若导入文件中存在与已有账号相同的手机号/学号，导入的新数据将覆盖旧数据</div>
            </div>
          </div>

          <!-- 上传文件：数据异常 -->
          <div v-else class="error-data-wrap">
            <div class="header">
              <div class="title">异常数据</div>
              <div class="count">
                <img
                  src="@/assets/img/error-warning-line.svg"
                  style="margin-right: 4px; width: 18px; height: 18px; vertical-align: text-bottom"
                />异常数量
                <span> {{ errorCount }}</span>
              </div>
            </div>
            <div class="content-detail">
              <div v-for="(item, index) in detailInfos" :key="index" class="detail-item">{{ item }}</div>
            </div>
          </div>
        </div>
        <!-- 2：预览数据 -->
        <div v-if="current === 1">
          <!-- <a-table :bordered="false" :pagination="false" :data-source="reviewData" :columns="reviewColumns" />
        </div> -->
          <!-- 3：导入数据 -->
          <!-- <div v-if="current === 2" style="width: 100%; height: 100%">
          <div v-if="percent !== 100" class="import-data">
            数据导入中..
            <a-progress :percent="percent" stroke-color="#1890FF" />
          </div> -->
          <div v-if="fileSuccess" class="success">
            <img src="@/assets/img/checkbox-circle-fill.svg" style="width: 36px; height: 36px" />
            <div class="content">数据导入完成</div>
            <div class="success-count">成功导入{{ successCount }}条数据</div>
            <a-button class="close" @click="handleCancel">关闭</a-button>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div v-if="current === 0 && !errorData">
        <a-button type="primary" :disabled="fileName.length <= 0" @click="next">下一步</a-button>
      </div>
      <div v-if="current === 0 && errorData">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="reUpload">重新上传</a-button>
      </div>
      <div v-if="current === 1">
        <!-- <a-button @click="previous">上一步</a-button>
        <a-button type="primary" @click="next">下一步</a-button> -->
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { ref } from 'vue'

  import { studentsManageApi } from '@/services/api'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false
    }
  })
  const emits = defineEmits<{ (e: 'cancel'): void }>()

  const current = ref<number>(0)
  const steps = [
    {
      title: '上传文件',
      content: 1
    },
    // {
    //   title: '预览数据',
    //   content: 2
    // },
    {
      title: '导入数据',
      content: 3
    }
  ]
  const items = steps.map(item => ({ key: item.title, title: item.title }))
  // 是否异常
  const errorData = ref<boolean>(false)
  // 异常数量
  const errorCount = ref<number>(0)
  // 异常内容
  const detailInfos = ref<string[]>([])

  const previous = () => {
    current.value--
  }

  // 下载模板
  const downloadTemplate = () => {
    window.open(`./files/学生导入模板.xlsx`, '_blank')
  }

  // 重新上传
  const reUpload = () => {
    errorData.value = false
  }
  const handleCancel = () => {
    current.value = 0
    percent.value = 0
    fileName.value = ''
    errorCount.value = 0
    errorData.value = false
    emits('cancel')
  }

  const fileList = ref<any>([])
  const fileName = ref<string>('')
  const fileSuccess = ref<boolean>(false)
  // 确认上传文件
  const next = async () => {
    let res = await studentsManageApi.fileUpload(
      { file: fileList.value[0].originFileObj },

      {
        noJudgeCode: true,
        headers: {
          'Content-Type': 'multipart/form-data',
          'hide-message': 'true'
        }
      }
    )
    if (res.code === 'AUTH-100075') {
      console.log('res', res.data.errorList)
      fileList.value = []
      fileName.value = ''
      errorData.value = true
      errorCount.value = res.data.abnormalCount
      detailInfos.value = res.data.errorList
      message.error(res.message)
    } else {
      current.value++
      fileSuccess.value = true
    }
  }
  const beforeUpload = (file: File) => {
    const isExcel = /\.(xls|xlsx)$/.test(file.name)
    const isSizeValid = file.size / 1024 / 1024 < 10 // 文件大小限制为10MB

    // 检查文件类型
    if (!isExcel) {
      // 使用 ant-design-vue 提供的消息组件显示错误信息

      message.error('请上传 Excel 文件（.xls 或 .xlsx）')
      fileName.value = ''
      fileList.value = []
      return false // 阻止上传
    }

    // 检查文件大小
    if (!isSizeValid) {
      fileName.value = ''
      fileList.value = []
      message.error('文件大小不得超过 10MB')
      return false // 阻止上传
    }
    fileName.value = file.name // 只保留一个文件
    console.log('将文件添加到本地的:', fileList.value)

    return false // 返回 false，防止调用上传接口
  }

  // 删除文件
  const delFile = () => {
    fileName.value = ''
    fileList.value = []
  }

  // 预览数据
  const reviewData = ref([
    {
      name: '章三',
      studentNumber: '24448488',
      telphone: '18487654884',
      class: '人工智能学院/人工智能技术应用/2024级卓越01班'
    }
  ])

  // 预览数据表格
  const reviewColumns = [
    {
      title: '学生姓名',
      dataIndex: 'name',
      width: 160
    },
    {
      title: '学号',
      dataIndex: 'studentNumber',
      width: 160
    },
    {
      title: '手机号码',
      dataIndex: 'telphone',
      width: 160
    },
    {
      title: '加入班级',
      dataIndex: 'class'
    }
  ]

  // 导入数据
  const percent = ref<number>(100)
  // 导入完成数
  const successCount = ref<number>(100)
</script>

<style lang="less" scoped>
  .bulk-import-modal {
    position: relative;
    height: 540px;

    // 步骤条中正在处理的图标
    :deep(.ant-steps .ant-steps-item-process .ant-steps-item-icon) {
      color: @text01 !important;
      background-color: rgba(255, 195, 112, 1) !important;
      border-color: transparent !important;
      vertical-align: middle;
    }

    // 步骤条中已完成图标
    :deep(.ant-steps .ant-steps-item-finish .ant-steps-item-icon) {
      color: @text01 !important;
      background-color: #fff !important;
      border-color: @border2 !important;
      vertical-align: middle;

      .ant-steps-icon {
        color: @border2 !important;
      }
    }

    // 步骤条中等待图标
    :deep(.ant-steps-item-wait .ant-steps-item-icon) {
      background-color: #fff !important;
      border-color: @border3 !important;
      vertical-align: middle;

      .ant-steps-icon {
        color: @border3 !important;
      }
    }

    :deep(.ant-steps) {
      .ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title {
        color: @text01 !important;
        font-weight: 700;

        &::after {
          background-color: @border2 !important;
        }
      }

      .ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title {
        font-weight: 700;
      }

      .ant-steps-item-icon {
        width: 24px;
        height: 24px;

        .ant-steps-icon {
          top: -4px;
        }
      }

      .ant-steps-item-content {
        vertical-align: middle !important;
      }
    }
    // 拖拽上传
    :deep(.ant-upload-wrapper .ant-upload-drag) {
      border: none !important;
    }

    // 进度条
    :deep(.ant-progress-bg) {
      height: 6px !important;
    }

    :deep(.ant-progress-line) {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    :deep(.ant-progress) {
      .ant-progress-text {
        margin-top: 18px;
        color: @text01;
      }
    }

    .steps-content {
      margin-top: 24px;

      .regular-data-wrap {
        .template-data {
          margin-bottom: 24px;
        }

        .file-upload {
          .ant-upload-text {
            margin-top: 16px;
            font-size: 12px;
            color: rgba(0, 0, 0, 0.75);
          }

          .filename-box {
            display: flex;
            justify-content: space-between;
            margin-top: 8px;

            .icon {
              &:hover {
                color: red;
              }
            }
          }
        }

        .special-tips {
          position: absolute;
          bottom: -24px;
          left: -32px;
          display: flex;
          align-items: center;
          padding-left: 20px;
          width: 1000px;
          height: 44px;
          background: #fffcf8;
          gap: 0 24px;

          .warning-title {
            font-weight: 700;
            display: flex;
            align-items: center;
            color: @text02;
          }

          .text {
            color: @text03;
          }
        }

        .title {
          margin-bottom: 8px;
          font-size: 16px;
          font-weight: 700;
          line-height: 36px;
        }

        .tips {
          display: flex;
          gap: 0 4px;
          margin-top: 18px;
          color: @text03;
          line-height: 22px;
        }
      }

      .error-data-wrap {
        .header {
          display: flex;
          align-items: center;
          gap: 8px 10px;
          height: 36px;

          .title {
            font-size: 16px;
            color: @text01;
            font-weight: 700;
            line-height: 24px;
          }

          .count {
            line-height: 22px;
            color: @text02;

            span {
              color: #e96d5c;
              font-weight: 700;
            }
          }
        }

        .content-detail {
          padding: 16px;

          .detail-item {
            margin-bottom: 12px;
            color: @text02;
          }
        }
      }

      .import-data {
        position: absolute;
        top: 50%;
        left: 50%;
        display: flex;
        align-items: center;
        width: 500px;
        font-size: 16px;
        color: @text01;
        transform: translate(-50%, -50%);
        flex-direction: column;
      }

      .success {
        position: absolute;
        top: 50%;
        left: 50%;
        display: flex;
        align-items: center;
        flex-direction: column;
        transform: translate(-50%, -50%);

        .content {
          margin-top: 4px;
          font-size: 16px;
          color: @text01;
          line-height: 24px;
        }

        .success-count {
          margin-top: 4px;
          font-size: 12px;
          line-height: 20px;
          color: @text03;
        }

        .close {
          margin-top: 12px;
          width: 60px;
        }
      }
    }
  }
</style>
